/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sistemavendas.dao;

import br.com.sistemavendas.util.JPAUtil;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

/**
 *
 * @author Elias
 */
public class GenericDAO<T, PK> implements InterfaceDAO<T, PK> {
    private final EntityManager entityManager;
   
    public GenericDAO() {
        this.entityManager = getEntityManager();
    }
    
    
    @Override
    public T getById(Class<T> classe, PK pk) {
        try {
            return entityManager.find(classe, pk);
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public boolean update(T entity) {
        boolean estate = false;
        try {
            entityManager.getTransaction().begin();
            entityManager.merge(entity);
            entityManager.getTransaction().commit();
            estate = true;
        } catch (Exception e) {
        }
        return estate;
    }

    @Override
    public T save(T entity) {
        T saved = null;
        try {
            entityManager.getTransaction().begin();
            saved = entityManager.merge(entity);
            entityManager.getTransaction().commit();
            return saved;
        } catch (Exception e) {
        }
        return saved;
    }

    @Override
    public boolean delete(T entity) {
        boolean estate = false;
        try {
            entityManager.getTransaction().begin();
            entityManager.remove(entity);
            entityManager.getTransaction().commit();
            estate = true;
        } catch (Exception e) {
        }
        return estate;
    }

    @Override
    public List<T> findAll(Class<T> classe) {
        return entityManager.createQuery("select o from " + classe.getSimpleName() + " o").getResultList();

    }

    @Override
    public EntityManager getEntityManager() {
        return JPAUtil.getEntityManager();
    }

}
